package util;

import gov.nasa.worldwind.geom.LatLon;

import java.util.List;

import cas.Identity;

import bean.RuteBean;

public class LengthMeasurer {
	
	public static double distanceBetween(Identity myIdentity, Identity anotherTrain, Integer[] sameId, boolean sameDirection){
		double anotherTrainDistance = 0;
		double myTrainDistance = 0;
		if(!sameDirection){
			anotherTrainDistance = distanceBetween(anotherTrain, sameId[0]);
			myTrainDistance = distanceBetween(myIdentity, sameId[0]);
			if(myIdentity.getCurRuteCoord().getId().equals(sameId[0]) && anotherTrain.getCurRuteCoord().getId().equals(sameId[0])){
				return LatLon.greatCircleDistance(myIdentity.getCurCoord(), anotherTrain.getCurCoord()).getDegrees();
			}else if(anotherTrain.getCurRuteCoord().getId().equals(sameId[0])){
				anotherTrainDistance = -anotherTrainDistance;
			}else if(myIdentity.getCurRuteCoord().getId().equals(sameId[0])){
				myTrainDistance =-myTrainDistance;
			}
			return anotherTrainDistance + myTrainDistance;	
		}else{
			if(anotherTrain.getCurRuteCoord().getId().equals(sameId[0])|
					myIdentity.getCurRuteCoord().getId().equals(sameId[0])){
				anotherTrainDistance = distanceBetween(anotherTrain, sameId[1]);
				myTrainDistance = distanceBetween(myIdentity, sameId[1]);
			}else{
				anotherTrainDistance = distanceBetween(anotherTrain, sameId[0]);
				myTrainDistance = distanceBetween(myIdentity, sameId[0]);
			}
			return Math.abs(anotherTrainDistance - myTrainDistance);
		}
	}
	
	public static double distanceBetween(Identity identity, Integer destId){
		List<RuteBean> listrute = identity.getRute();
		int destUrutan = RuteUtil.getUrutanWhereCoordId(listrute, destId);
		int currentUrutan = identity.getUrutan();
		double totalDistance = LatLon.greatCircleDistance(identity.getCurCoord(), listrute.get(currentUrutan).getCoordinate()).getDegrees();
		if(destUrutan==currentUrutan){
			return totalDistance;
		}
		int iterator = destUrutan<currentUrutan?-1:1;
		currentUrutan = currentUrutan + iterator;
		
		while((iterator ==-1?(currentUrutan>destUrutan):(currentUrutan<destUrutan))){
			totalDistance = totalDistance + LatLon.greatCircleDistance(listrute.get(currentUrutan).getCoordinate(), listrute.get(currentUrutan+iterator).getCoordinate()).getDegrees();
			currentUrutan = currentUrutan + iterator;
		}
		return totalDistance;
	}
}
